<?php

namespace App\Logic\Group;

use App\Core\BaseCore;
use App\Core\BaseModel;
use App\Core\Output;
use App\Model\Group\GroupProfitModel;
use App\Util\ArrayHelper;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\Component\Di;
use EasySwoole\Component\Singleton;
use EasySwoole\Http\Request;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\Redis\Redis;
use Throwable;

class GroupProfitService extends BaseCore
{

    use Singleton;

    /**更新用户团队收益*/
    public function profit($member_id, $child_id, $score) {
        /**如果有符合的记录,那么在原来的记录上累加
         * 如果没有,那么新建记录
         * */
        DbManager::getInstance()->startTransactionWithCount('write');
        try {
            if ($profit = GroupProfitModel::create()->getOne(['member_id' => $member_id, 'child_id' => $child_id])) {
                $profit = GroupProfitModel::create()->connection('write')->lockForUpdate()->get($profit->id);
                $data  = [
                    'profit' => bcadd($profit->profit, $score, 2),
                ];
                $profit = GroupProfitModel::create()->updateData($data, ['id' => $profit->id]);
            } else {
                $data   = [
                    'member_id' => $member_id,
                    'child_id'  => $child_id,
                    'score'     => $score,
                ];
                $profit = GroupProfitModel::create()->insertData($data);
            }
            DbManager::getInstance()->commitWithCount('write');
            return $profit;
        } catch (\Throwable $e) {
            DbManager::getInstance()->rollbackWithCount('write');
            CommonHelper::logException($e, '更新用户团队收益错误');
            throw $e;
        }

    }
}
